<template>
  <div class="department-management">
    <div class="page-header">
      <h3>部门管理</h3>
      <p>管理组织架构，包括新建、移动、编辑和删除部门</p>
    </div>

    <div class="content-container">
      <div class="toolbar">
        <el-button type="primary" @click="handleCreateDepartment">
          <el-icon><Plus /></el-icon>
          新建部门
        </el-button>
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>

      <div class="department-tree">
        <el-tree
          ref="departmentTreeRef"
          :data="departmentData"
          :props="treeProps"
          :expand-on-click-node="false"
          default-expand-all
          node-key="id"
        >
          <template #default="{ node, data }">
            <div class="tree-node">
              <div class="node-info">
                <el-icon><OfficeBuilding /></el-icon>
                <span class="node-label">{{ data.name }}</span>
                <span class="node-count">({{ data.memberCount || 0 }}人)</span>
              </div>
              <div class="node-actions">
                <el-button type="primary" size="small" @click="handleAddSubDepartment(data)">
                  新建下属部门
                </el-button>
                <el-button type="success" size="small" @click="handleMoveDepartment(data)">
                  移动部门
                </el-button>
                <el-button type="warning" size="small" @click="handleEditDepartment(data)">
                  编辑部门
                </el-button>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="handleDeleteDepartment(data)"
                  :disabled="data.children && data.children.length > 0"
                >
                  删除部门
                </el-button>
              </div>
            </div>
          </template>
        </el-tree>
      </div>
    </div>

    <!-- 新建/编辑部门对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="departmentForm" :rules="departmentRules" ref="departmentFormRef" label-width="100px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="departmentForm.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="上级部门" prop="parentId" v-if="!isEditMode">
          <el-tree-select
            v-model="departmentForm.parentId"
            :data="departmentTreeData"
            :props="treeSelectProps"
            placeholder="请选择上级部门"
            style="width: 100%"
            check-strictly
            clearable
          />
        </el-form-item>
        <el-form-item label="部门描述" prop="description">
          <el-input 
            v-model="departmentForm.description" 
            type="textarea" 
            rows="3"
            placeholder="请输入部门描述" 
          />
        </el-form-item>
        <el-form-item label="负责人" prop="manager">
          <el-input v-model="departmentForm.manager" placeholder="请输入负责人姓名" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 移动部门对话框 -->
    <el-dialog v-model="moveDialogVisible" title="移动部门" width="500px">
      <el-form :model="moveForm" :rules="moveRules" ref="moveFormRef" label-width="100px">
        <el-form-item label="当前部门">
          <el-input :value="movingDepartment?.name" disabled />
        </el-form-item>
        <el-form-item label="目标上级" prop="targetParentId">
          <el-tree-select
            v-model="moveForm.targetParentId"
            :data="availableParents"
            :props="treeSelectProps"
            placeholder="请选择新的上级部门"
            style="width: 100%"
            check-strictly
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="moveDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleMoveSubmit">确定移动</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, OfficeBuilding } from '@element-plus/icons-vue'

// 响应式数据
const departmentTreeRef = ref()
const departmentFormRef = ref()
const moveFormRef = ref()
const dialogVisible = ref(false)
const moveDialogVisible = ref(false)
const editingDepartment = ref(null)
const movingDepartment = ref(null)

// 表单数据
const departmentForm = reactive({
  name: '',
  parentId: null,
  description: '',
  manager: ''
})

const moveForm = reactive({
  targetParentId: null
})

// 表单验证规则
const departmentRules = {
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' }
  ]
}

const moveRules = {
  targetParentId: [
    { required: true, message: '请选择目标上级部门', trigger: 'change' }
  ]
}

// 树形配置
const treeProps = {
  children: 'children',
  label: 'name'
}

const treeSelectProps = {
  children: 'children',
  label: 'name',
  value: 'id'
}

// 计算属性
const dialogTitle = computed(() => {
  return editingDepartment.value ? '编辑部门' : '新建部门'
})

const isEditMode = computed(() => {
  return !!editingDepartment.value
})

// 部门数据
const departmentData = ref([
  {
    id: 1,
    name: '总公司',
    memberCount: 50,
    description: '公司总部',
    manager: '张三',
    children: [
      {
        id: 2,
        name: '技术部',
        memberCount: 20,
        description: '负责技术研发',
        manager: '李四',
        children: [
          {
            id: 3,
            name: '前端组',
            memberCount: 8,
            description: '前端开发',
            manager: '王五'
          },
          {
            id: 4,
            name: '后端组',
            memberCount: 12,
            description: '后端开发',
            manager: '赵六'
          }
        ]
      },
      {
        id: 5,
        name: '人事部',
        memberCount: 10,
        description: '人力资源管理',
        manager: '钱七',
        children: [
          {
            id: 6,
            name: '招聘组',
            memberCount: 5,
            description: '人才招聘',
            manager: '孙八'
          }
        ]
      },
      {
        id: 7,
        name: '财务部',
        memberCount: 8,
        description: '财务管理',
        manager: '周九'
      }
    ]
  }
])

// 用于选择的部门树数据（排除当前编辑的部门）
const departmentTreeData = computed(() => {
  const filterDepartment = (data, excludeId = null) => {
    return data.filter(item => item.id !== excludeId).map(item => ({
      ...item,
      children: item.children ? filterDepartment(item.children, excludeId) : []
    }))
  }
  
  const excludeId = editingDepartment.value?.id || movingDepartment.value?.id
  return filterDepartment(departmentData.value, excludeId)
})

// 可移动到的父部门（排除自己和子部门）
const availableParents = computed(() => {
  if (!movingDepartment.value) return departmentTreeData.value
  
  const excludeIds = new Set()
  const addChildrenIds = (dept) => {
    excludeIds.add(dept.id)
    if (dept.children) {
      dept.children.forEach(addChildrenIds)
    }
  }
  addChildrenIds(movingDepartment.value)
  
  const filterData = (data) => {
    return data.filter(item => !excludeIds.has(item.id)).map(item => ({
      ...item,
      children: item.children ? filterData(item.children) : []
    }))
  }
  
  return filterData(departmentData.value)
})

// 方法
const handleCreateDepartment = () => {
  editingDepartment.value = null
  dialogVisible.value = true
  Object.assign(departmentForm, {
    name: '',
    parentId: null,
    description: '',
    manager: ''
  })
}

const handleAddSubDepartment = (data) => {
  editingDepartment.value = null
  dialogVisible.value = true
  Object.assign(departmentForm, {
    name: '',
    parentId: data.id,
    description: '',
    manager: ''
  })
}

const handleEditDepartment = (data) => {
  editingDepartment.value = data
  dialogVisible.value = true
  Object.assign(departmentForm, {
    name: data.name,
    parentId: data.parentId,
    description: data.description || '',
    manager: data.manager || ''
  })
}

const handleMoveDepartment = (data) => {
  movingDepartment.value = data
  moveDialogVisible.value = true
  moveForm.targetParentId = null
}

const handleDeleteDepartment = async (data) => {
  if (data.children && data.children.length > 0) {
    ElMessage.warning('请先删除子部门')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除部门"${data.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 递归删除部门
    const deleteDepartment = (tree, targetId) => {
      for (let i = 0; i < tree.length; i++) {
        if (tree[i].id === targetId) {
          tree.splice(i, 1)
          return true
        }
        if (tree[i].children && deleteDepartment(tree[i].children, targetId)) {
          return true
        }
      }
      return false
    }
    
    deleteDepartment(departmentData.value, data.id)
    ElMessage.success('删除成功')
  } catch {
    // 用户取消删除
  }
}

const handleSubmit = async () => {
  try {
    await departmentFormRef.value.validate()
    
    if (editingDepartment.value) {
      // 编辑部门
      Object.assign(editingDepartment.value, {
        name: departmentForm.name,
        description: departmentForm.description,
        manager: departmentForm.manager
      })
      ElMessage.success('部门更新成功')
    } else {
      // 新建部门
      const newDepartment = {
        id: Date.now(),
        name: departmentForm.name,
        description: departmentForm.description,
        manager: departmentForm.manager,
        memberCount: 0,
        children: []
      }
      
      if (departmentForm.parentId) {
        // 添加到指定父部门
        const addToParent = (tree, parentId, dept) => {
          for (let item of tree) {
            if (item.id === parentId) {
              if (!item.children) item.children = []
              item.children.push(dept)
              return true
            }
            if (item.children && addToParent(item.children, parentId, dept)) {
              return true
            }
          }
          return false
        }
        addToParent(departmentData.value, departmentForm.parentId, newDepartment)
      } else {
        // 添加为根部门
        departmentData.value.push(newDepartment)
      }
      
      ElMessage.success('部门创建成功')
    }
    
    dialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const handleMoveSubmit = async () => {
  try {
    await moveFormRef.value.validate()
    
    // 移动部门逻辑
    const moveDepartment = (tree, deptId, targetParentId) => {
      // 先找到要移动的部门并从原位置删除
      let targetDept = null
      const removeDept = (tree, id) => {
        for (let i = 0; i < tree.length; i++) {
          if (tree[i].id === id) {
            targetDept = tree.splice(i, 1)[0]
            return true
          }
          if (tree[i].children && removeDept(tree[i].children, id)) {
            return true
          }
        }
        return false
      }
      
      removeDept(tree, deptId)
      
      if (targetDept) {
        if (targetParentId) {
          // 添加到新父部门
          const addToParent = (tree, parentId, dept) => {
            for (let item of tree) {
              if (item.id === parentId) {
                if (!item.children) item.children = []
                item.children.push(dept)
                return true
              }
              if (item.children && addToParent(item.children, parentId, dept)) {
                return true
              }
            }
            return false
          }
          addToParent(tree, targetParentId, targetDept)
        } else {
          // 移动到根级别
          tree.push(targetDept)
        }
      }
    }
    
    moveDepartment(departmentData.value, movingDepartment.value.id, moveForm.targetParentId)
    
    moveDialogVisible.value = false
    ElMessage.success('部门移动成功')
  } catch (error) {
    console.error('移动失败:', error)
  }
}

const handleRefresh = () => {
  ElMessage.info('数据已刷新')
}

onMounted(() => {
  // 初始化数据
})
</script>

<style scoped>
.department-management {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e5e7eb;
}

.page-header h3 {
  margin: 0 0 8px 0;
  color: #1f2937;
  font-size: 20px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.content-container {
  background: #f8fafc;
  border-radius: 8px;
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  gap: 12px;
}

.department-tree {
  background: white;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #e5e7eb;
}

.tree-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 8px 0;
}

.node-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.node-label {
  font-weight: 500;
  color: #374151;
}

.node-count {
  color: #6b7280;
  font-size: 12px;
}

.node-actions {
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.3s;
}

.tree-node:hover .node-actions {
  opacity: 1;
}

:deep(.el-tree-node__content) {
  padding: 0;
  height: auto;
}

:deep(.el-tree-node__content:hover) {
  background: #f3f4f6;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
